package com.uzhie.web.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uzhie.util.PayloadBeanUtil;
import com.uzhie.web.bean.*;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 * Created by TangFei on 2018/7/18.
 * 参数修改，剥离消息体，封装返回结果
 * 包括请求参数、响应参数
 */
public class PayloadAspect {

    public PayloadBean run(ProceedingJoinPoint point) throws Throwable {
        Object[] reqArgs = point.getArgs();
        RequestBean requestBean = JSONObject.parseObject(JSON.toJSONString(reqArgs[0]), RequestBean.class);
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        Object[] methodArgs = new Object[method.getParameterTypes().length];
        for (int i = 0; i < method.getParameterTypes().length; i++) {
            if (method.getParameterTypes()[i] == JSONObject.class) {
                methodArgs[i] = requestBean.getRequestBody();
            } else if (method.getParameterTypes()[i] == PageBean.class) {
                methodArgs[i] = requestBean.getPage();
            } else {
                continue;
            }
        }
        Object resp = null;
        try {
            resp = PayloadBeanUtil.getInstance().buildPayload(ResponseBean.class, requestBean, (ResponseBodyBean<? extends Object>) point.proceed(methodArgs), 200, "请求成功");
        } catch (RuntimeException e) {
            e.printStackTrace();
            resp = PayloadBeanUtil.getInstance().buildPayload(ResponseBean.class, requestBean, null, 500, e.getMessage());
        } finally {
            return (PayloadBean) resp;
        }
    }

}
